<?php


namespace app\madmin\service;

use app\madmin\model\CommissionAssessment;
use app\madmin\model\IntegralRecord;
use app\madmin\model\RechargeRecord;
use app\madmin\model\UserCash;
use app\madmin\model\UserCoupon;
use app\madmin\model\Agent;
use app\madmin\model\AgentGrade;
use app\madmin\model\CommissionActivity;
use app\madmin\model\CommissionActivityAward;
use app\madmin\model\Coupon;
use app\sadmin\service\LicenseService;
use think\Console;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Db;

class CommissionActivityService
{

    public function __construct()
    {
        $this->close();

        #CommissionActivity::update(['status' => 3], $over_where);
        // 调用命令行的指令

    }

    /**列表
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function list($page, $size)
    {
//        $license="eyJwdinvIWJsaWNfa2V5IjoiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cclxuTUlHZk1BMEdDU3FHU0liM0RRRUJBUVVBQTRHTkFEQ0JpUUtCZ1FEQ2JVajVcL25XRWRSUzlpMU1va3IzK2l1Mm1cclxuWjZCUzlPc0cxYUpWS0NiN1h0NWozQmIyNytzZWZuMCsxUVFhZVwvNmlsS3VYZjUza0p3QnVUd3BoOXJQTGFVam1cclxuXC9xTjNUazgrdkt1OGczblJkTTVWN2V3TnlndG1NSzRCZ0V5UnZWMSsycVpZRHBOQklTYWhwamJsOVNZR1ZRUnJcclxuVGtGOWY4WHRcL0JYeVhtOEl5UUlEQVFBQlxyXG4tLS0tLUVORCBQVUJMSUMgS0VZLS0tLS0iLCJsaWNlbnNlIjoiTXpqRTJtQlBWSWNLQUhycWo1MTMrWlhYZ2J5NmtBVFJGbVZjazdERUJHNVNXc0JtZ0JuNEFHdmRsVUpQeTVFR0V2d3NQZEIzUHNzSitlVTRFTjNPSVdHbzdnS0ZCTkw4NzVpRDlmVHR4T0cyRldZSjl1TUhmb05sZkMrZjNDZHdRQ0d0bHprVVlMK2V4aWk5R0Z5bUtaVWpEZ092d0plaHAzY240VEp4bWZvPSJ9";
//        $licenseService=new LicenseService();
//        $resArr = json_decode(base64_decode(substr_replace($license, "", 5, 4)), true);
////        $decrypt = $this->decrypt($resArr['license'], $resArr['public_key']);
//
//        $decrypt =$licenseService->decrypt($resArr['license'], $resArr['public_key']);
//        dd($decrypt);

        $where = [];
        $data = request()->get();
        !empty($data['name']) && $where[] = ['name|content', 'like', '%' . $data['name'] . '%'];
        !empty($data['status']) && $where[] = ['status', '=', $data['status']];
        !empty($data['start_time']) && $where[] = ['start_time', '>=', $data['start_time']];
        !empty($data['end_time']) && $where[] = ['end_time', '<=', $data['end_time']];


        $res = CommissionActivity::where($where)->order('id', 'desc')->paginate(['page' => $page, 'list_rows' => $size]);
        foreach ($res as $activity) {
            list($http, $d) = $this->checkActiveSchedule($activity);
            $activity['total'] = $d['total'];
            $activity['success_num'] = $d['success_num'];
        }
        return [HTTP_SUCCESS, $res];
    }

    /**详情
     * @param int $id
     * @return int
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function detail(int $id)
    {

        $find = CommissionActivity::find($id);

        return [HTTP_SUCCESS, $find];
    }


    /**添加
     * @param array $data
     * @return array
     */
    public function add()
    {
        list($http, $msg) = $this->checkRole();

        if ($http != 200) {
            return [$http, $msg];
        }
        $data = request()->post();

        $data['create_time']=date("Y-m-d H:i:s",time());
        $model = new CommissionActivity();
        $model->create($data);
//        setAttributes($model, $data);
        return [HTTP_SUCCESS, $model];
    }


    /**
     * 删除
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function delete($id)
    {

        $model = CommissionActivity::find($id);

        if (empty($model)) {
            return [HTTP_NOTACCEPT, '删除失败'];
        }
        $model->delete();
        return [HTTP_SUCCESS, $model];
    }

    /**
     * 状态变更
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function status()
    {
        $status = request()->post('status');
        $id = request()->post('id');
        if (!in_array($status, [1, 2, 3, 4])) {
            return [HTTP_NOTACCEPT, '请求参数异常'];
        }
        $model = CommissionActivity::find($id);
        if (!$model) {
            return [HTTP_NOTACCEPT, '该记录不存在'];
        }
        #当希望恢复活动时 必选保证活动是处于暂停中的活动
        if ($status == 1) {
            if ($model->status != 2) {

                return [HTTP_NOTACCEPT, '只有暂停的任务可以恢复进行中'];
            }
        }
        if ($status == 2) {
            if (!in_array($model->status, [0, 1])) {

                return [HTTP_NOTACCEPT, '只有未进行或进行中的活动才能暂停'];
            }
            $model->stop_time = date('Y-m-d H:i:s');

            $model->save();
        }
        if($status==4 || $status ==3){
            return [HTTP_NOTACCEPT, '该活动已结束或关闭'];
        }
        $model = CommissionActivity::update(['status' => $status], ['id' => $id]);
        return [HTTP_SUCCESS, $model];
    }

    /**列表
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function award($page, $size)
    {
        $where = [];
        $data = request()->get();
        !empty($data['name']) && $where[] = ['name|content', 'like', '%' . $data['name'] . '%'];
        !empty($data['status']) && $where[] = ['status', '=', $data['status']];
        !empty($data['create_time']) && $where[] = ['create_time', '>=', $data['create_time']];

        $data = CommissionActivityAward::where($where)->with(['agent' => function ($query) {
            $query->with('grade');
        }, 'activity'])->order('id', 'desc')->paginate(['page' => $page, 'list_rows' => $size]);

        foreach ($data as $item => $value) {
            if (!empty($value->content)) {
                $content = json_decode($value->content, true);
                if (isset($content['coupon']) && is_array($content['coupon'])) {
                    $coupons = Coupon::where('id', 'in', $content['coupon'])->select()->toArray();
                    $content['coupons'] = $coupons;
                }
                $value->content = $content;
            }
        }
        return [HTTP_SUCCESS, $data];
    }

    #测试发放奖励
    public function send()
    {

        $id = request()->post('id');
        global $user;
        $mid = $user->mall_id;
        $activity = CommissionActivity::where(['id' => $id,'status'=>3])->find();
        if($activity){
            return $this->over_activity($activity,true);
        }
        return [HTTP_NOTACCEPT, '该奖励已全部发放或找不到该记录'];

    }

    public function checkActiveSchedule($activity)
    {
        global $user;
        if (empty($activity)) {
            return [HTTP_NOTACCEPT, '无此活动'];
        }
        $where = [["create_time", ">", $activity->start_time], ["create_time", "<", $activity->end_time], ["mall_id", '=', $activity->mall_id]];

        $award_role = CommissionActivity::getAwardRole($activity);
        #规则总数
        $role_count = count($award_role);
        if (empty($award_role)) {
            return [HTTP_NOTACCEPT, '没有有效的奖励规则'];
        }
        $agents = CommissionActivity::agents($activity->mall_id, $activity);
        $list = [];
        $debugs = [];
        $list['total'] = count($agents);
        $list['success_num'] = 0;
        foreach ($agents as $ak => $agent) {
            // 下级用户人数
            $user_count = CommissionActivity::getUsers($agent['id'], $where);
            //销售额
            $payment = CommissionActivity::getPayment($agent['id'], $where);
            //下级分销商数
            $agents_count = CommissionActivity::getAgents($agent['id'], $where);
            //下级订单总数
            $order_count = CommissionActivity::getOrderCount($agent['id'], $where);
            $d['user_count'] = $user_count;
            $d['pay_ment'] = $payment;
            $d['agent_count'] = $agents_count;
            $d['order_count'] = $order_count;
            $d['agent'] = $agent->toArray();
            $d['award_role'] = $award_role;

            #从高到底去奖励
            for ($i = $role_count - 1; $i >= 0; $i--) {
                if (!isset($award_role[$i])) {
                    break;
                }
                $role_info = $award_role[$i];
                $condition = $role_info['condition'] ?? [];

                if (!empty($condition['child_count']) && $condition['child_count'] >= $user_count) {
                    continue;
                }
                if (!empty($condition['order_count']) && $condition['order_count'] >= $order_count) {
                    continue;
                }
                if (!empty($condition['order_money']) && $condition['order_money'] >= $payment) {
                    continue;
                }
                if (!empty($condition['child_agent_count']) && $condition['child_agent_count'] >= $agents_count) {
                    continue;
                }
                $list['success_num']++;
                break;
            }
            $debugs[] = $d;
        }
        return [HTTP_SUCCESS, $list];
    }

    public function close()
    {
        $key = "activity_lock";

        if (Cache::get($key)) {
            return false;
        }
        $time = date("Y-m-d H:i:s");
        $where = [
            ['start_time', '<', $time],
            ['end_time', '>', $time],
            ['status', '=', 0]
        ];
        #活动开始的自动变更状态
        CommissionActivity::update(['status' => 1], $where);
        #活动结束的自动变更
        $over_where = [
            ['end_time', '<', $time],
            ['status', 'in', [0, 1, 2]]
        ];


        $over_list = CommissionActivity::where($over_where)->select();

        if (count($over_list)>0) {
            $output = \think\facade\Console::call('order_end', []);
            $output->fetch();
//            sleep(1);
            $output = \think\facade\Console::call('agent_get_money', []);
            $output->fetch();

            // 获取输出信息
            #$output->fetch();
        }

        foreach ($over_list as $over_activity) {
            $this->over_activity($over_activity, false);
        }
        Cache::set($key, 1, 10);
    }

    public function over_activity($activity, $is_issue = false)
    {

        if (empty($activity)) {
            return [HTTP_NOTACCEPT, '无此活动'];
        }
//        if ($activity->status != 3) {
//            return [HTTP_NOTACCEPT, '当活动结束时才能发放'];
//        }
        $where = [["create_time", ">", $activity->start_time], ["create_time", "<", $activity->end_time], ["mall_id", '=', $activity->mall_id]];

        $award_role = CommissionActivity::getAwardRole($activity);
        #规则总数
        $role_count = count($award_role);
        if (empty($award_role)) {
            return [HTTP_NOTACCEPT, '没有有效的奖励规则'];
        }
        $agents = CommissionActivity::agents($activity->mall_id, $activity);
        $list = [];
        $debugs = [];

        foreach ($agents as $ak => $agent) {
            // 下级用户人数
            $user_count = CommissionActivity::getUsers($agent['id'], $where);
            //销售额
            $payment = CommissionActivity::getPayment($agent['id'], $where);
            //下级分销商数
            $agents_count = CommissionActivity::getAgents($agent['id'], $where);
            //下级订单总数
            $order_count = CommissionActivity::getOrderCount($agent['id'], $where);
            $d['user_count'] = $user_count;
            $d['pay_ment'] = $payment;
            $d['agent_count'] = $agents_count;
            $d['order_count'] = $order_count;
            $d['agent'] = $agent->toArray();
            $d['award_role'] = $award_role;

            #从高到底去奖励
            for ($i = $role_count - 1; $i >= 0; $i--) {
                if (!isset($award_role[$i])) {
                    break;
                }
                $role_info = $award_role[$i];
                $condition = $role_info['condition'];
                if (!empty($condition['child_count']) && $condition['child_count'] >= $user_count) {
                    continue;
                }
                if (!empty($condition['order_count']) && $condition['order_count'] >= $order_count) {
                    continue;
                }
                if (!empty($condition['order_money']) && $condition['order_money'] >= $payment) {
                    continue;
                }
                if (!empty($condition['child_agent_count']) && $condition['child_agent_count'] >= $agents_count) {
                    continue;
                }

                //满足了就发放奖励
                $this->give_reward($activity, $agent, $role_info['award'], $is_issue);
                $d['success'] = [
                    'activity' => $activity,
                    'agent' => $agent->toArray(),
                    'role_info' => $role_info
                ];
                break;
            }
            $debugs[] = $d;
        }
        $activity->stop_time = date('Y-m-d H:i:s');
        $activity->status = 4;
        $activity->save();
        return [HTTP_SUCCESS, '发放成功'];
    }

    public function give_reward($activity, $agent, $reward, $is_issue = false)
    {

        #写入活动奖励
        $write_data = [
            'activity_id' => $activity->id ?? 0,
            "content" => json_encode($reward),
            "agent_id" => $agent->id,
            "level_id" => $agent->grade_id,
        ];
        if ($is_issue) {
            #发放优惠券
            if (!empty($reward['coupon'])) {
                $this->coupon($agent, $reward['coupon']);
            }
            #发放余额
            if (!empty($reward['balance'])) {
                $this->amount($agent, $reward['balance']);
            }
            #发放积分
            if (!empty($reward['integral'])) {
                $this->integral($agent, $reward['integral']);
            }
            #分销等级升级
            if (!empty($reward['upgrade'])) {
                $this->upgrade($agent);
            }
            $write_data['status']=1;
        }

        CommissionActivityAward::write($write_data);

    }

    public function issue()
    {
        $id = request()->post('id');
        $awardModel = CommissionActivityAward::where(['id' => $id, 'status' => 0])->find();
        if (!$awardModel) {
            return [HTTP_NOTACCEPT, "数据异常"];
        }
        $reward = json_decode($awardModel->content, true);
        $agent = Agent::find($awardModel->agent_id);

        #发放优惠券
        if (!empty($reward['coupon'])) {
            $this->coupon($agent, $reward['coupon']);
        }
        #发放余额
        if (!empty($reward['balance'])) {
            $this->amount($agent, $reward['balance']);
        }
        #发放积分
        if (!empty($reward['integral'])) {
            $this->integral($agent, $reward['integral']);
        }
        #分销等级升级
        if (!empty($reward['upgrade'])) {
            $this->upgrade($agent);
        }
        $awardModel->status = 1;
        $awardModel->save();


        return [HTTP_SUCCESS, "发放成功"];

    }

    protected function integral($agent, int $value): void
    {
        $mid = $agent->mall_id;
        IntegralRecord::create([
            'mall_id' => $mid,
            'integral' => $value,
            'type' => 13,
            'status' => 1,
            'number' => 0,
            'commodity_id' => 0,
            'sku_id' => 0,
            'order_id' => 0,
            'user_id' => $agent['user_id'],
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s')
        ]);
        UserCash::where('user_id', $agent['user_id'])
            ->inc('integral', $value)
            ->inc('integral_total', $value)
            ->update(['update_time' => date('Y-m-d H:i:s')]);
    }

    protected function amount($agent, int $value): void
    {
        $mid = $agent->mall_id;
        $money = $value;
        #$money = floor($value / 100);
        $total = UserCash::where('user_id', $agent['user_id'])->value('total');
        RechargeRecord::create([
            'mall_id' => $mid,
            'user_id' => $agent['user_id'],
            'base_in' => '',#$baseIn,
            'source_type' => 10,
            'source' => '分销达标奖励获得',
            'is_online' => 0,
            'type' => 0,
            'card' => '{}',
            'money' => $money,
            'service_charge' => 0,
            'remark' => '分销达标奖励获得' . $money,
            'trade' => '',
            'pay_no' => '',
            'status' => 1,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
            'new_cash' => $total + $money,
            'old_cash' => $total
        ]);
        UserCash::where('user_id', $agent['user_id'])
            ->inc('total', $money)
            ->update(['update_time' => date('Y-m-d H:i:s')]);
    }

    protected function coupon($agent, array $coupons): void
    {
        $mid = $agent->mall_id;

        foreach ($coupons as $coupon_id) {
            $coupon = Coupon::where(['id' => $coupon_id, 'status' => 1])->find();
            if ($coupon) {
                UserCoupon::create([
                    'mall_id' => $mid,
                    'user_id' => $agent['user_id'],
                    'coupon_id' => $coupon['id'],
                    'merchant_id' => $coupon['merchant_id'],
                    'type' => 2,
                    'status' => 0
                ]);
            }
        }
    }

    protected function upgrade($agent)
    {
        #todo 分销等级升级
        if ($agent) {
            $grade_id = $agent->grade_id;
            $next_grade = AgentGrade::where("mall_id", $agent->mall_id)
                ->where('status', 1)
                ->where('delete_time', null)
                ->where('id', '>', $grade_id)
                ->order('id')
                ->find();
            if ($next_grade) {
                $agent->grade_id = $next_grade->id;
                $agent->save();
            }
        }
    }

    /**
     * * 考核自动发放佣金
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function GetMoney()
    {
        $config = Db::name('configuration')
            ->where('type', 'tradeSetting')
            ->select()
            ->toArray();
        $user = $ids = [];
        foreach ($config AS $index => $item) {
            $agent_get_money_time = json_decode($item['configuration'], true)['agent_get_money_time'];
            $select = Db::name('agent_bill_temporary')
                ->field('id,user_id,commission,amount,uniqid,order_id,order_no,commodity_id,order_commodity_id,sku_id,source_user_id,number,money')
                ->where('order_commodity_id', 'IN', function ($sql) use ($agent_get_money_time, $item) {
                    $sql->name('order_commodity')
                        ->field('id')
                        ->where('mall_id', $item['mall_id'])
                        ->where('update_time', '<', date('Y-m-d H:i:s', time() - $agent_get_money_time * 86400))
                        ->where('delete_time IS NULL')
                        ->where('status', 4);
                })
                ->where('mall_id', $item['mall_id'])
                ->where('assessment_status', 0)
                ->where('is_assessment', 1)
                ->select()
                ->toArray();
            $id = array_column($select, 'id');
            $temp = [];
            foreach ($select AS $key => $value)
                $temp[$value['user_id']][] = $value['commission'];
            foreach ($temp AS $key => $value)
                $user[$key] = array_sum($value);
            $ids = array_merge($ids, $id);
        }
        try {
            Db::startTrans();
            foreach ($user AS $key => $value)
                Db::name('user_cash')
                    ->where('user_id', $key)
                    ->inc('assessment_total', $value)
                    ->inc('assessment', $value)
                    ->update(['update_time' => date('Y-m-d H:i:s')]);
            Db::name('agent_bill_temporary')
                ->where('id', 'IN', $ids)
                ->update(['assessment_status' => 1, 'update_time' => date('Y-m-d H:i:s')]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    public function checkRole()
    {
        $data = request()->post();

        if ($data['end_time'] < $data['start_time']) {
            return [HTTP_NOTACCEPT, "结束日期不能低于开始日期"];
        }

//        list($code,$msg)=$this->is_exists();
//        if($code!=200){
//            return [$code,$msg];
//        }

        $role = request()->post('award_stage');

        $role_arr = json_decode($role, true);

        $role_keys = ["first", 'second', 'third'];
        $count = count($role_arr);
        for ($i = $count - 1; $i >= 0; $i--) {
            if ($i == 0) {
                return [HTTP_SUCCESS, "成功"];
            } else {

                foreach ($role_arr[$role_keys[$i]] as $item => $v) {

                    $condition = $role_arr[$role_keys[$i]]['condition'];

                    $condition1 = $role_arr[$role_keys[$i - 1]]['condition'];

                    foreach ($condition as $condition_k => $condition_v) {
                        if ($condition[$condition_k] < $condition1[$condition_k]) {
                            return [HTTP_NOTACCEPT, "高阶达标条件 不能低于低阶"];
                        }
                    }
                }

            }
        }

        return [HTTP_SUCCESS, "成功"];
    }

    public function is_exists()
    {
        $data = request()->post();

        $model = CommissionActivity::where([['end_time', '>', $data['start_time']], ['status', 'in', [0, 1]], ['level_type', '=', 0]])->find();
        if ($model) {
            return [HTTP_NOTACCEPT, "已存在达标活动,请先结束达标活动"];
        }

        $where = [['end_time', '>', $data['start_time']], ['status', 'in', [0, 1]]];

        $assessments = CommissionActivity::where($where)->select()->toArray();

        $levels = array_column($assessments, 'levels');
        $level_arr = [];
        foreach ($levels as $item => $value) {
            $level_arr = array_merge($level_arr, json_decode($value));
        }
        $level_ids = array_unique(array_values($level_arr));

        $request_level_data = json_decode($data['levels'], true);

        foreach ($request_level_data as $level) {
            if (in_array($level, $level_ids)) {
                return [HTTP_NOTACCEPT, "该分销等级已存在达标活动,请先结束达标活动"];
            }
        }
        return [HTTP_SUCCESS, "success"];
    }

}